﻿using AutoMapper;
using Basic.Traceability.Domain.Freed;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Freed.BreedingInformation;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Freed.BreedingInformation
{
    public class CreateBreedingInformationHandler : IRequestHandler<CreateBreedingInformationCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BreedingInformationModel> breedinformationRepository;
        private readonly ILogger<CreateBreedingInformationHandler> logger;
        private readonly IMapper mapper;

        public CreateBreedingInformationHandler(IBaseRepository<BreedingInformationModel> breedinformationRepository, ILogger<CreateBreedingInformationHandler> logger, IMapper mapper)
        {
            this.breedinformationRepository = breedinformationRepository;
            this.logger = logger;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加养殖信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateBreedingInformationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<BreedingInformationModel>(request);
            model.Id=YitIdHelper.NextId();
            var r = breedinformationRepository.Create(model);
            if(r>0)
            {
                res.Msg= "添加养殖信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("添加养殖信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg= "添加种养信息失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                logger.LogError("添加养殖信息失败");
                return Task.FromResult(res);
            }
        }
    }
}
